//手机号正则验证
function checkPhone (val) {
  let regex = /^1[3456789]{1}\d{9}$/;
  if (val == "") {
    return { valid: false, msg: "手机号不能为空" };
  } else if (regex.test(val)) {
    return { valid: true, msg: "" };
  } else {
    return { valid: false, msg: "手机号格式不正确" };
  }
}
// 身份证验证
function checkIdCard (val) {
  const regex =
    /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
  if (val == "") {
    return { valid: false, msg: "身份证号码不能为空" };
  } else if (regex.test(val)) {
    return { valid: true, msg: "" };
  } else {
    return { valid: false, msg: "请输入正确的身份证号码" };
  }
}
//金额验证//大于0
function validateAmount (val) {
  if (!val) {
    return { valid: false, msg: "金额不能为空" };
  }

  const amountRegex = /^(?!0+(?:\.0+)?$)\d+(?:\.\d{1,2})?$/;

  if (!amountRegex.test(val)) {
    if (/^0+(?:\.0+)?$/.test(val)) {
      return { valid: false, msg: "金额必须大于0" };
    }
    if (/,/.test(val)) {
      return { valid: false, msg: "金额不能包含逗号" };
    }
    if (!/^\d+(?:\.\d{1,2})?$/.test(val)) {
      return { valid: false, msg: "金额最多保留2位小数" };
    }
    return { valid: false, msg: "金额格式不正确" };
  }
  return { valid: true, msg: "" };
}
//正整数验证
function isPositiveInteger (val) {
  const regex = /^[1-9]\d*$/;
  if (regex.test(val)) {
    return { valid: true, msg: "" };
  } else {
    return { valid: false, msg: "请输入纯正整数" };
  }
}
//生成18位随机数
function generateRandomId (num) {
  const chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const randomValues = new Uint32Array(num || 18);
  crypto.getRandomValues(randomValues);
  return Array.from(randomValues)
    .map((n) => chars[n % chars.length])
    .join("");
}
//统一信用代码验证
function validateCreditCode (code) {
  if (!code || typeof code !== "string") {
    return { valid: false, message: "统一信用代码不能为空" };
  }

  // 基本格式校验
  const creditCodeRegex =
    /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
  if (!creditCodeRegex.test(code)) {
    return {
      valid: false,
      message: "统一信用代码格式错误",
    };
  }
  return { valid: true, message: "统一信用代码有效" };
}
export default {
  checkPhone,
  checkIdCard,
  validateAmount,
  isPositiveInteger,
  generateRandomId,
  validateCreditCode,
};
